/* eslint-disable no-param-reassign */
import {
  currentUserInfo,
  loginApi,
  logoutApi
} from '@/api/login'

import userApi from '@/api/modules/system/user'
import {
  ACCESS_TOKEN
} from '@/store/mutationTypes'
import lodash from 'lodash'
// import router from '@/router'
import testRoutes from '@/router/test'
// import i18n from '@/lang'
const jwtDecode = require('jwt-decode')
// 权限标识提取和路由菜单重组
let recordFirstMenuIndex = 0
let recordFirstMenu = ''
function routePermissionTag(permissionItem, routeMenu, permissionTags, grandpaItem, parent) {
  permissionItem.map((item, index) => {
    let curParent;
    if (!parent) {
      curParent = [];
    } else {
      curParent = [...parent]
    }
    //   路由和菜单数据(按钮上也可能对应的是新页面，所以不用type===1来判断，而是path只要有值)
    let childRoutes = [];
    let meta = {
      title: item.title,
      icon: item.icon,
      affix: item.path === '/dashboard',
      hasChildMenus: item.childMenus.length,
      active: item.active,
      breadList: curParent
    };
    if (item.path) {
      recordFirstMenuIndex = recordFirstMenuIndex + 1
      if (recordFirstMenuIndex === 1) {
        recordFirstMenu = item.path
      }
      const buttonWithPage = item.type === 2
      let redirect = null
      if (item.component === '/layouts/pageView') {
        redirect = item.childMenus && item.childMenus.length > 0 ? item.childMenus[0].path : null
      } else if (item.childMenus && item.childMenus.length > 0 && item.childMenus.filter(m => m.type === 1).length > 0) {
        //有子菜单，自身又是页面的，需要嵌套pageView(router-view)，加入到子菜单
        childRoutes.push({
          path: '',
          name: item.router,
          component: loadView(item.component),
          meta: {
            title: item.title,
            icon: item.icon,
            affix: item.path === '/dashboard',
            hasChildMenus: item.childMenus.length,
            active: item.active,
            breadList: curParent,
            bread: false
          },
        })
        item.component = '/layouts/pageView';
        item.router += '__parent';
        redirect = item.path + '/';
      }
      // 是按钮绑定的新页面路由需要添加到父节点的父节点上
      const appendToNode = buttonWithPage ? grandpaItem : routeMenu;
      let routeItem = {
        path: item.path,
        name: item.router,
        redirect,
        component: loadView(item.component),
        meta: meta,
        children: childRoutes,
        display: buttonWithPage ? false : item.display
      };
      appendToNode.push(
        routeItem
      )
      curParent.push(routeItem.meta.title);
    }
    // 权限标识提取
    if (permissionTags && item.code) {
      permissionTags.push(item.code)
    }
    if (item.childMenus && item.childMenus.length > 0) {
      routePermissionTag(item.childMenus, childRoutes, permissionTags, routeMenu, curParent)
    }
  })
}
function loadView(view) {
  // 组件懒加载
  return resolve => require([`@/views${view}`], resolve)
}
const initQueryParams = {
  account: '',
  name: '',
  organizationIds: [],
  roleIds: []
}
function getRoutePermissionTag(menus) {
  const menuJson = JSON.parse(JSON.stringify(menus))
  const routeMenu = []
  const permissionTags = []
  try {
    routePermissionTag(menuJson, routeMenu, permissionTags)
  } catch (e) {
    console.error(e)
  }
  return { routeMenu, permissionTags }
}

function getUserColors() {
  // eslint-disable-next-line max-len
  const tagColors = ['2BB080', 'FF8762', '8A8A8A', '58ABCE', '5470C6', '68748B', '9E53A6', 'A67032', '6CA63A', 'B18B73', 'D96641', 'A6A032', '1B4759', 'FEA443', '705E78']
  const maxIndex = tagColors.length - 1
  const colors = {}
  for (let i = 0; i < 25; i = i + 1) {
    colors[String.fromCharCode(i + 65)] = '#' + tagColors[i % maxIndex]
  }
  return colors
}

const user = {
  state: {
    token: '',
    name: '', // 用户名称
    loginCode: '', // 登录账号
    userId: '',
    permissionTags: [], // 权限标识
    addRouters: [], // 动态路由
    firstPath: '', // 拥有权限的第一个路径
    extendS1: '', // 强制修改密码 or修改密码
    extendS2: '', // 修改密码原因
    userData: [], // 用户列表数据
    // 用户查询条件
    queryParams: lodash.cloneDeep(initQueryParams),
    loadingUserData: false,
    userColors: getUserColors(),
    // 登录用户当前所选项目id
    myActiveProjectId: sessionStorage.getItem('myActiveProjectId') || '',
    // 用户基本信息(email,remark,name,account,id等)
    userInfo: {}
  },

  mutations: {
    RESET_USER_STATE: (state) => {
      state.token = ''
      sessionStorage.removeItem(ACCESS_TOKEN)
      state.name = ''
      state.loginCode = ''
      state.userId = ''
      state.permissionTags = []
      state.addRouters = []
      state.extendS1 = '' // 强制修改密码 or修改密码
      state.extendS2 = '' // 修改密码原因
    },
    SET_TOKEN: (state, token) => {
      state.token = token
      sessionStorage.setItem(ACCESS_TOKEN, token)
    },
    SET_NAME: (state, {
      name
    }) => {
      state.name = name
    },
    SET_LONGINCODE: (state, loginCode) => {
      state.loginCode = loginCode
    },
    SET_USERID: (state, userid) => {
      state.userId = userid
    },
    SET_permissionTags: (state, permissionTags) => {
      state.permissionTags = permissionTags
    },
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers // 动态菜单路由
    },
    SET_FIRST_ROUTE: (state, routePath) => {
      state.firstPath = routePath
    },
    SET_extendS1: (state, extendS1) => {
      state.extendS1 = extendS1
    },
    SET_extendS2: (state, extendS2) => {
      state.extendS2 = extendS2
    },
    SET_USER_DATA(state, data) {
      state.userData = data
    },
    SET_LOADING_USER_DATA(state, data) {
      state.loadingUserData = data
    },
    SET_MY_ACTIVE_PROJECT_ID(state, data) {
      state.myActiveProjectId = data
      sessionStorage.setItem('myActiveProjectId', data)
    },
    resetUserQueryParams(state) {
      state.queryParams = { ...initQueryParams }
    },
    setUserInfo(state, data) {
      state.userInfo = data
    }
  },

  actions: {
    // 登录
    Login({
      commit
    }, userInfo) {
      return new Promise((resolve, reject) => {
        loginApi(userInfo).then(response => {
          commit('SET_TOKEN', response.data.token)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({
      commit
    }) {
      return new Promise((resolve, reject) => {
        const data = jwtDecode(sessionStorage.getItem(ACCESS_TOKEN))
        console.log(data)
        currentUserInfo().then(res => {
          console.log(res, 'GetInfo')
          const menus = []
          const { data } = res
          if (Array.isArray(data.menus) && data.menus.length > 0) {
            menus.push(...data.menus)
          }
          commit('SET_NAME', data.name)
          commit('SET_LONGINCODE', data.account)
          commit('SET_USERID', data.id)
          commit('setUserInfo', {
            id: data.id,
            account: data.account,
            name: data.name,
            email: data.email,
            phone: data.phone,
            remark: data.remark,
            // enabled: data.enabled,
            projects: data.projects || [],
            roles: data.roles || [],
            position: data.position
          })
          //   commit('SET_extendS1', data.extend_s1)
          //   commit('SET_extendS2', data.extend_s2)
          let permissionTag = getRoutePermissionTag(menus);
          const permissionTags = permissionTag.permissionTags
          const routeMenu = permissionTag.routeMenu
          commit('SET_permissionTags', permissionTags)
          commit('SET_ROUTERS', routeMenu.concat(testRoutes));
          commit('SET_FIRST_ROUTE', recordFirstMenu)
          resolve(res.data)
        }).catch(err => {
          reject(err)
        })
      })
    },

    // 登出
    Logout({
      state
    }) {
      return new Promise((resolve) => {
        logoutApi({ token: state.token }).then(() => {
          sessionStorage.removeItem(ACCESS_TOKEN)
          resolve()
        }).catch(() => {
          resolve()
        })
      })
    },

    // 添加用户
    // eslint-disable-next-line no-unused-vars
    addUserData({ commit }, data) {
      return new Promise((resolve, reject) => {
        userApi.addUser(data).then(res => {
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 编辑用户
    // eslint-disable-next-line no-unused-vars
    editUserData({ commit }, data) {
      return new Promise((resolve, reject) => {
        userApi.editUser(data).then(res => {
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 删除用户
    // eslint-disable-next-line no-unused-vars
    deleteUserData({ commit }, data) {
      return new Promise((resolve, reject) => {
        userApi.deleteUser(data).then(res => {
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 重置用户密码
    // eslint-disable-next-line no-unused-vars
    resetUserPwdData({ commit }, data) {
      return new Promise((resolve, reject) => {
        userApi.resetUserPwd(data).then(res => {
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 启用与停用用户密码
    // eslint-disable-next-line no-unused-vars
    enableUserData({ commit }, data) {
      return new Promise((resolve, reject) => {
        userApi.enableUser(data).then(res => {
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 获取分页用户数据
    getUserPageData({ commit }, data) {
      commit('SET_LOADING_USER_DATA', true)
      commit('SET_USER_DATA', [])
      return new Promise((resolve, reject) => {
        userApi.getUserPageData(data).then(res => {
          commit('SET_USER_DATA', res.data)
          resolve(res)
        }).catch(err => {
          reject(err)
        }).finally(() => {
          commit('SET_LOADING_USER_DATA', false)
        })
      })
    }

  }
}

export default user
